package com.rocketmq.producer.tx;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;

/**
 * @program: awesome-spring
 * @description:
 * @author: Alex Wu
 * @createDate: 2025-02-11 16:23
 **/
@RocketMQTransactionListener
public class TransactionMsgListener implements RocketMQLocalTransactionListener
{
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 执行本地事务
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg,
                                                                 Object obj)
    {
        System.out.println("start execute local rocketMQ transaction");
        RocketMQLocalTransactionState resultState = RocketMQLocalTransactionState.COMMIT;

        try
        {
            //处理业务
            String jsonStr = new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8);
            System.out.println("start local transaction：" + jsonStr);
            System.out.println("insert order info：" + jsonStr);
            System.out.println("local commit or rollback：" + jsonStr);
//            int a = 1 / 0 ; //模拟异常
        }
        catch (Exception e)
        {
            System.out.println("invoke local mq trans error: " + e);
            resultState = RocketMQLocalTransactionState.ROLLBACK;
        }

        return resultState;
    }

    /**
     * 检查本地事务的状态
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg)
    {
        System.out.println("start check Local rocketMQ transaction");

        RocketMQLocalTransactionState resultState = RocketMQLocalTransactionState.COMMIT;

        try
        {
            String jsonStr = new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8);
            // 用msg 的ID 反查
            System.out.println("check if order exist：" + jsonStr);
            System.out.println("decide commit or rollback：" + jsonStr);
        }
        catch (Exception e)
        {
            resultState  = RocketMQLocalTransactionState.ROLLBACK;
        }
        return resultState;
    }
}

